/*
 *  cmd_echo.h
 *  edrift
 *
 *  Created by Yudi Rosandi on 3/16/12.
 *  Copyright 2012 TU-Kaiserslautern. All rights reserved.
 *
 */

// syntax:
// echo "string to say"
// echo every=loop-counter step=domain elapsed=domain avg=domain.array avg=buffer

void cmd_echo(istringstream& ss) {
  
  // FIXME! writing strings...
  
  string tok,msg;
  ofstream ofl;
  bool usefile=false;
  
  string sff(ss.str());
  int red=sff.find('>');
  
  if(red!=sff.npos) {
    if(sff.find(">>")!=sff.npos) { // append
      sff.erase(0,red+2);
      ofl.open(remove_char(sff,' ').c_str(),std::ios_base::app);
      usefile=true;
    } else { // truncate
      sff.erase(0,red+1);
      ofl.open(remove_char(sff,' ').c_str());
      usefile=true;
    }
  }
  
  while(ss>>tok) {
    if(tok[0]=='>') break;
    int at=tok.find('(');
    int cfd=current;
    
    if(at!=tok.npos) {
      string op=tok.substr(0,at);
      tok.erase(0,at+1);
      tok=remove_char(tok,"()");
                  
      if(op=="step") {
        int usefd=cfd;
        if(tok!="") {
          cfd=search_fd(tok);
          if(cfd<0) throw (string("echo step() domain not found: ")+tok).c_str();
        }
        tok.assign(as_string(fd[cfd]->solver->GetStep()));
      }
      
      else if(op=="sum") {
        Buffer b;
        get_buffer(b,tok);
        if(b.empty) throw(string("echo sum() buffer not found: ")+tok).c_str();
        tok.assign(as_string(fd[cfd]->solver->GetSum(b.ptr)));
      }

      else if(op=="avg") {
        Buffer b;
        get_buffer(b,tok);
        if(b.empty) throw(string("echo avg() buffer not found: ")+tok).c_str();
        tok.assign(as_string(fd[cfd]->solver->GetAverage(b.ptr)));
      }
      
      else if(op=="time"||op=="elapsed") {
        if(tok!="") {
          cfd=search_fd(tok);
          if(cfd<0) throw (string("step time() domain not found: ")+tok).c_str();
        }
        
        tok.assign(as_string(fd[cfd]->solver->GetStep()*fd[cfd]->solver->GetTimestep()));
        
      }
      
      else throw "invalid token@echo";
      
    }
    
    msg.append(tok+" ");
    
  }
  
  if(me==0) {
    if(usefile) {
      ofl<<msg<<std::endl;
      ofl.close();
    } else
      std::cout<<msg<<std::endl;
  }
  
}
